//
//  SLPageScrollTitleView.m
//  SLPageView
//
//  Created by 王胜利 on 2018/11/13.
//  Copyright © 2018 wsl. All rights reserved.
//  跟随滑动标题栏(标题宽度自适应文字宽度)
//

#define WEAK(type)   __weak typeof(type) weak##type = type;

////////////////////////////尺寸相关////////////////////////////
#define SCREEN_SIZE \
([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? CGSizeMake([UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale,[UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale) : [UIScreen mainScreen].bounds.size)
//获取屏幕宽度与高度
//#define SCREEN_WIDTH SCREEN_SIZE.width
//#define SCREEN_HEIGHT SCREEN_SIZE.height

#import "SLPageScrollTitleView.h"
#import "Masonry.h"
#import "SLPageBaseScrollView.h"
#import "SLPageManager.h"
#import "SLBadgeButton.h"
//#import "ThemeKit.h"

@interface SLPageScrollTitleView ()

/// 滑动标题栏
@property (nonatomic, strong) SLPageBaseScrollView *titleScrollView;
/// 滑动的线
@property (nonatomic, strong) UIView *scrollLine;
/// 按钮数组
@property (nonatomic, strong) NSMutableArray <UIView *>* btns;

@end

@implementation SLPageScrollTitleView


@synthesize pageEntitys = _pageEntitys;
@synthesize titleBtnSelect = _titleBtnSelect;
@synthesize currentIdx = _currentIdx;

- (instancetype)init{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor redColor];
//        self.titleScrollView.scrollEnabled = NO;
        self.lineColor = UIColor.darkGrayColor;
        self.titleNormalColor = UIColor.darkGrayColor;
        self.titleSelectColor = UIColor.blackColor;
    }
    return self;
}

- (void)setPageEntitys:(NSArray<SLPageEntity *> *)pageEntitys{
    _pageEntitys = pageEntitys;
    [self setTitlesAndThemeColor];
}

- (void)setLineColor:(UIColor *)lineColor{
    _lineColor = lineColor;
    self.scrollLine.backgroundColor = lineColor;
}

- (void)setTitleNormalColor:(UIColor *)titleNormalColor{
    _titleNormalColor = titleNormalColor;
    [self resetTitleColor];
}

- (void)setTitleSelectColor:(UIColor *)titleSelectColor{
    _titleSelectColor = titleSelectColor;
    [self resetTitleColor];
}

/// MARK: - 重设标题颜色
- (void)resetTitleColor{
    for (UIButton *btn in self.btns) {
        UIColor *color = (btn.tag == self.currentIdx+100)?self.titleSelectColor:self.titleNormalColor;
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
}

#pragma mark - 更新布局
- (void)layoutSubviews{
    /// 布局滑动的线
    [self layoutScrollLine];
    [self.titleScrollView layoutIfNeeded];
    [super layoutSubviews];
}

#pragma mark 初始化标题和主题色
- (void)setTitlesAndThemeColor{
    /// 设置标题
    for (int i = 0 ; i < self.pageEntitys.count; i++) {
        UIView *lastView;
        if (self.btns.count > 0) {
            lastView = self.btns.lastObject;
        }

        SLPageEntity *pageEntity = self.pageEntitys[i];
        SLBadgeButton *button = [self createTitleButtnWithIndex:i];
        button.pageEntity = pageEntity;
        [self.titleScrollView addSubview:button];
        [self.btns addObject:button];
        /// 标题宽
        CGFloat titleWidth = [pageEntity.title boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 35) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.width;

        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.centerY.equalTo(self.titleScrollView);
            make.width.mas_equalTo(titleWidth+20);
            if (lastView) {
                make.left.equalTo(lastView.mas_right);
            }else{
                make.left.equalTo(self.titleScrollView);
            }
            /// 最后一个添加距右的约束
            if (i == self.pageEntitys.count-1){
                make.right.equalTo(self.titleScrollView);
            }
        }];
    }

    [self.titleScrollView layoutIfNeeded];
    self.titleScrollView.scrollEnabled = (self.titleScrollView.contentSize.width > self.bounds.size.width);
}

/// MARK: - 创建标题按钮
- (SLBadgeButton *)createTitleButtnWithIndex:(NSUInteger)idx{
    SLBadgeButton *button = [SLBadgeButton buttonWithType:UIButtonTypeCustom];
    button.tag = idx+100;
    UIColor *color = idx == 0? self.titleSelectColor:self.titleNormalColor;
    [button setTitleColor:color forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button addTarget:self action:@selector(titleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

/// MARK: - 标题按钮点击事件
- (void)titleBtnAction:(UIButton *)btn{
    NSInteger i = btn.tag - 100;
    [self scrollToIndex:i animated:NO];
    self.titleBtnSelect(i);
}

/// MARK: - 修改badge未读消息数
- (void)titleBadge:(NSString *)badge idx:(NSInteger)idx{
    SLBadgeButton *btn = (SLBadgeButton *)self.btns[idx];
    btn.badge = badge;
}
/// MARK: - 是否显示标题栏红点
- (void)isShowRedPoint:(BOOL)isShow idx:(NSInteger)idx{
    SLBadgeButton *btn = (SLBadgeButton *)self.btns[idx];
    btn.isShowRedPoint = isShow;
}


#pragma mark 根据Idx设置顶部按钮的背景颜色和位置
- (void)scrollToIndex:(NSInteger)idx animated:(BOOL)animated{
    /// 如果下标相同，即不需要切换分页的时候直接返回
    if (self.currentIdx == idx) {
        return;
    }
    self.currentIdx = idx;

    [self layoutScrollLine];
    WEAK(self)
    [UIView animateWithDuration:0.2 animations:^{
        /// 2.设置选中按钮的颜色改变
        [weakself resetTitleColor];

        /// 3.自动滑动TitleScroll
        if (weakself.titleScrollView.contentSize.width > weakself.titleScrollView.bounds.size.width) {
            UIView *view = self.btns[idx];
            CGFloat btnCenterX = view.center.x;
            CGFloat headerScrollWidth = weakself.titleScrollView.bounds.size.width;
            if (btnCenterX > headerScrollWidth/2 && (weakself.titleScrollView.contentSize.width - btnCenterX) > headerScrollWidth/2) {
                weakself.titleScrollView.contentOffset = CGPointMake(btnCenterX - headerScrollWidth/2, 0);
            }else if (btnCenterX < headerScrollWidth/2){
                weakself.titleScrollView.contentOffset = CGPointMake(0, 0);
            }else if ((weakself.titleScrollView.contentSize.width - btnCenterX) < headerScrollWidth/2){
                weakself.titleScrollView.contentOffset = CGPointMake(weakself.titleScrollView.contentSize.width-headerScrollWidth, 0);
            }
        }

        [weakself layoutIfNeeded];
    }];
}

#pragma mark - 布局滑动的线
- (void)layoutScrollLine{
    [self.titleScrollView layoutIfNeeded];
    /// 标题宽
    CGFloat titleBtnX = [self.btns[self.currentIdx] frame].origin.x;
    CGFloat btnWidth = self.btns[self.currentIdx].bounds.size.width;
    CGFloat titleWidth = [self.pageEntitys[self.currentIdx].title boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 35) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.width;
    CGFloat lineXOffset = titleBtnX +(btnWidth - titleWidth)/2;
    [self.scrollLine mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(titleWidth);
        make.left.equalTo(self.titleScrollView).offset(lineXOffset);
    }];
}

#pragma mark - lazyload
- (SLPageBaseScrollView *)titleScrollView{
    if (!_titleScrollView) {
        _titleScrollView = [SLPageBaseScrollView new];
        _titleScrollView.showsVerticalScrollIndicator = NO;
        _titleScrollView.showsHorizontalScrollIndicator = NO;
        _titleScrollView.bounces = NO;
        [self addSubview:_titleScrollView];
        [_titleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self);
            make.height.mas_equalTo(@45);
            make.bottom.equalTo(self).offset(0);
        }];
    }
    return _titleScrollView;
}
- (UIView *)scrollLine{
    if (!_scrollLine) {
        _scrollLine = [UIView new];
        [self.titleScrollView addSubview:_scrollLine];
        [_scrollLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@1.5);
            make.width.mas_equalTo(@0);
            make.bottom.equalTo(self.titleScrollView);
        }];
    }
    return _scrollLine;
}

- (NSMutableArray<UIView *> *)btns{
    if (!_btns) {
        _btns = [NSMutableArray array];
    }
    return _btns;
}


@end
